//
//  WBComposeController.swift
//  sinaWeibo
//
//  Created by 吴熠 on 16/11/21.
//  Copyright © 2016年 吴熠. All rights reserved.
//

import UIKit
import SVProgressHUD

private let base = 1000

enum buttonType:Int {
    case Picture = 1000
    case Atperson
    case Topic
    case Emoji
    case More
}

var selectorVC : WBPictureSelectorController = {
    let flowlayout = UICollectionViewFlowLayout()
    flowlayout.itemSize = CGSize(width: selectorItemWidth, height: selectorItemWidth)
    flowlayout.minimumLineSpacing = selectorMargin
    flowlayout.minimumInteritemSpacing = selectorMargin
    flowlayout.sectionInset = UIEdgeInsetsMake(selectorMargin, selectorMargin, 0, selectorMargin)
    let vc = WBPictureSelectorController(collectionViewLayout: flowlayout)
    return vc
}()

class WBComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)

        setupUI()
        setTitleView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        //来判断是否要显示图片视图
        selectorVC.view.isHidden = selectorVC.selectorImages.count == 0
    }
    
    
    //dismiss掉控制器
    func miss(){
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    
    //创建UI界面
    func setupUI(){
        //添加关闭按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(miss))
        self.navigationItem.rightBarButtonItem = self.sendBtn
        //添加textView
        self.view.addSubview(textView)
        self.textView.addSubview(placeholder)
        self.placeholder.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
        self.setupToolBar()
        //注册通知
        registerNotification()
        
        self.addChildViewController(selectorVC)
        self.view.addSubview(selectorVC.view)
        //约束
        selectorVC.view.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.textView.snp.bottom)
            make.bottom.equalTo(self.toolBar.snp.top)
        }
        selectorVC.collectionView?.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    }
    
    //注册接收键盘变化的通知
    private func registerNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(selectEmotion(n:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
    }
    @objc private func selectEmotion(n : Notification){
        guard let em = n.object as? HMEmoticon else {
            //点击的就是删除
            //执行回删
            textView.deleteBackward()
            return
        }
        //判断如果点击的是emoji标签
        if em.type == 1 {
            //将emoji表情添加到对应的文本中
            textView.replace(textView.selectedTextRange!, withText: em.emojiStr ?? "")
            return
        }
        //处理图片表情
        textView.inputEmoticon(em: em)
        
    }
    
    
    @objc private func keyboardChanged(noti:NSNotification){
//        print(noti)
        let endFrame = noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        //计算出bottom将要更新后的bottom距离底部的值
        //因为是网上移动,所以计算的值要取反
        let offsetVertic = -(kScreenH-endFrame.origin.y)
        
        //动画更新约束
        UIView.animate(withDuration: 0.25) {
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view.snp.bottom).offset(offsetVertic)
            })
        }

        self.view.layoutIfNeeded()

        
    }
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    
    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
        return barButtonItem
    }()
    //懒加载编辑框
    lazy var textView : HMEmoticonTextView = {
        let tv = HMEmoticonTextView(frame: CGRect.zero)
//        tv.text = "分享新鲜事"
        tv.frame = CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH/3)
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.backgroundColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1)
        tv.delegate = self
        //设置textView的这两个属性就可以使键盘收回
        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
        
        return tv
    }()
    
    //用lable做一个placeholder提示文字
    lazy var placeholder : UILabel = {
        let lbl = UILabel(title: "分享新鲜事...", fontSize: 18, textColor: UIColor.lightGray)
        lbl.sizeToFit()
        return lbl
    }()
    
    
    private func setupToolBar(){
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for (index,img) in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage(named:img), for: .normal)
            btn.backgroundColor = UIColor(white: 0.8, alpha: 1)
            btn.sizeToFit()
            //点击事件的方法
            btn.tag = index + base
            btn.addTarget(self, action: #selector(btnDicClick(button:)), for: .touchUpInside)
            toolBar.addArrangedSubview(btn)
        }
        
    }
    //toolBar的点击事件
    @objc private func btnDicClick(button : UIButton){
        //根据报错转换类型
        let enumType = buttonType.init(rawValue: button.tag)!
        switch enumType {
        case buttonType.Picture:
            print("点击了图片")
            //直接调用picturecontroller的代理方法
            selectorVC.willAddPicture(cell: nil)
        case buttonType.Atperson:
            print("点击了艾特")
        case buttonType.Topic:
            print("点击了话题")
        case buttonType.Emoji:
            print("点击了表情")
            if !textView.isFirstResponder{
                textView.becomeFirstResponder()
            }
            //设置inputView完成键盘的切换
            textView.inputView = (textView.inputView == nil ? keyoardView : nil)
            //刷新输入视图
            textView.reloadInputViews()
        case buttonType.More:
            print("点击了更多")
        }
    }
    
    
    //懒加载toolBar
    lazy var toolBar: UIStackView = {
        let bottomBar = UIStackView(frame: CGRect.zero)
        //设置方向
        bottomBar.axis = .horizontal
        //内部的填充的方式--->fillEqually等宽填充
        bottomBar.distribution = .fillEqually
        return bottomBar
    }()
    
    
    
    
    //点击发送按钮的方法
    func sendBtnDidClick(){
        //发送微博
//        print("发送微博")
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let access_token = WBUserAccountViewModel.shared.userAccount?.access_token
        let parameters = ["access_token":access_token,"status":textView.imageEmoticon2Chs()]
        //判断是否有图片
        if selectorVC.selectorImages.count == 0 {
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "发布失败")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发布成功")
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: { 
                self.miss()
            })
        }
        }else{
            //发布图片微博
            let urlstring = "https://upload.api.weibo.com/2/statuses/upload.json"
            //图片微博
            let imageData = UIImagePNGRepresentation(selectorVC.selectorImages.first!)
            HMNetworkTools.shared.post(urlstring, parameters: parameters, constructingBodyWith: { (formdata) in
                //将需要上传的二进制数据拼接到formdata中
                //withFileData:需要上传的文件的二进制数据
                //name:服务器接收的字段 "pic"
                //fileName:服务器存储的名称,新浪微博的服务器会对用户上传的图片按照自己的规则进行处理
               //mimeType:标识文件类型
                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "woaini", mimeType: "application/octet-stream")
                
            }, progress: nil, success: { (_, result) in
                
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
                
            }, failure: { (_, error) in
                SVProgressHUD.showError(withStatus: "发布图片微博失败")
            })
        }
        
    }
    
    //设置导航栏的titleView
    private func setTitleView(){
        let titleLbl = UILabel()
        titleLbl.textAlignment = .center
        titleLbl.numberOfLines = 0
        if let username = WBUserAccountViewModel.shared.userAccount?.name {
            let titleText = "发布微博\n\(username)"
            titleLbl.text = titleText
            //截取字符串,修改属性文本,用可变
            let strM = NSMutableAttributedString(string: titleText)
            //获取要改变的那一段字(用户名)的范围
            let range = (titleText as NSString).range(of: username)
            //添加属性
            strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName:UIColor.orange], range: range)
            titleLbl.attributedText = strM
            
        }else
        {
            //没有登录的情况下显示文字
            titleLbl.text = "发布微博"
        }
        titleLbl.sizeToFit()
        self.navigationItem.titleView = titleLbl
    }
    
    
    //自定义键盘视图
    lazy var keyoardView : HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    
    
}


extension WBComposeController : UITextViewDelegate{
    //textView的代理方法
    func textViewDidChange(_ textView: UITextView) {
        //让发送按钮高亮
        sendBtn.isEnabled = textView.hasText
        //让占位文字消失
        self.placeholder.isHidden = textView.hasText
    }
    
}

